#include <cstdlib>
#include <iostream>

#include <Ice/Ice.h>
#include <IceStorm/IceStorm.h>
#include "eventSupplier.h"
#include "event.h"

EventSupplier::EventSupplier(::Ice::CommunicatorPtr& c, const std::string& host)
{
	comm = c;
	
	createSupplier(host);
}

EventSupplier::~EventSupplier()
{
	
}

void EventSupplier::push(const ::Collaboration::Event& evt,
                  const Ice::Current& c)
{	
	supplier->push(evt);
}

void EventSupplier::subscribe(const ::Collaboration::EventConsumerPrx& ec,
               const Ice::Current& c)
{
	topic->subscribeAndGetPublisher(IceStorm::QoS(), ec);
}

void EventSupplier::unsubscribe(const ::Collaboration::EventConsumerPrx& ec,
               const Ice::Current& c)
{
	topic->unsubscribe(ec);
}

void EventSupplier::createSupplier(const std::string& host)
{
	char aux[256];
	sprintf(aux, "DemoIceStorm/TopicManager:tcp -h %s -p 10000", host.c_str());
	IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(
	        comm->stringToProxy(aux));
	
    if(!manager)
    {
        std::cerr << "Invalid supplier proxy" << std::endl;
        exit(1);
    }

    try
    {
        topic = manager->retrieve("events");
    }
    catch(const IceStorm::NoSuchTopic&)
    {
        try
        {
            topic = manager->create("events");
        }
        catch(const IceStorm::TopicExists&)
        {
            std::cerr << "Temporary failure. try again." << std::endl;
            exit(1);
        }
    }

    Ice::ObjectPrx publisher = topic->getPublisher();
    publisher = publisher->ice_oneway();

    supplier = Collaboration::EventSupplierPrx::uncheckedCast(publisher);
}
